package microservice.registory;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * @program: rocsun
 * @description: TCP探测
 * @author: yx.guo
 * @create: 2025-08-07 22:24
 **/
public class TcpProbe {
    // 主机地址
    private final String host;
    // 端口号
    private final int port;
    // 间隔时间
    private final long interval;
    // 调度器
    private final ScheduledExecutorService scheduler;
    // 超时时间
    private final int timeout;
    // 失败重试次数
    private int failedAttempts = 0;
    // 最大失败重试次数
    private final int maxFailedAttempts;

    public TcpProbe(String host, int port, long intervalSeconds, int timeoutMs, int maxFailedAttempts) {
        this.host = host;
        this.port = port;
        this.interval = intervalSeconds;
        this.timeout = timeoutMs;
        this.maxFailedAttempts = maxFailedAttempts;
        this.scheduler = Executors.newSingleThreadScheduledExecutor();
    }

    public void start() {
        scheduler.scheduleAtFixedRate(this::probe, 0, interval, TimeUnit.SECONDS);
    }

    /**
     * 探测
     */
    private void probe() {
        try (Socket socket = new Socket()) {
            socket.connect(new InetSocketAddress(host, port), timeout);
            failedAttempts = 0;
            System.out.println("TCP probe successful to " + host + ":" + port);
        } catch (IOException e) {
            handleFailure();
        }
    }

    /**
     * 处理失败
     */
    private void handleFailure() {
        failedAttempts++;
        System.out.println("TCP probe failed. Attempt " + failedAttempts + "/" + maxFailedAttempts);

        if (failedAttempts >= maxFailedAttempts) {
            System.err.println("Max failed attempts reached. Host unreachable.");
            // 可以触发重连或其他恢复逻辑
            scheduler.shutdown();
        }
    }

    public static void main(String[] args) {
        TcpProbe probe = new TcpProbe("example.com", 80, 5, 3000, 3);
        probe.start();
    }
}
